
import { getOffsetTop, getWinScrollTop, getWinHeight } from './util';

/**滚动自动播放动画的区域配置和列表*/
var scrollAniAreas = {
    'ani-left-enter': {
        areas: [],
        enter: function (el) {
            el.style.left = '0';
        },
        exit: function (el) {
            el.style.left = '-100vw';
        },
    },
    'ani-right-enter': {
        areas: [],
        enter: function (el) {
            el.style.right = '0';
        },
        exit: function (el) {
            el.style.right = '-100vw';
        },
    },
    'ani-opacity-enter': {
        areas: [],
        enter: function (el) {
            el.style.opacity = 1;
        },
        exit: function (el) {
            el.style.opacity = 0;
        },
    },
}
var scrollAniAreasLoad = false;


/**刷新页面所有滚动动画区域元素数据*/
function refreshScrollAniAreas() {
    for (let aniName in scrollAniAreas) {
        let cfg = scrollAniAreas[aniName];
        let els = document.getElementsByClassName(aniName);
        cfg.areas.length = 0;
        for (let el of els) {
            cfg.areas.push({
                in: false,
                el: el,
                top: getOffsetTop(el),
                height: el.offsetHeight,
            })
        }
    }
    scrollAniAreasLoad = true;
}
/**触发滚动动画的区域*/
function emitScrollAniAreas() {
    if (!scrollAniAreasLoad) return;
    var top = getWinScrollTop();
    var height = getWinHeight();
    //中间区域算是进入区域(1/6~5/6之间)
    var areaStart = top + height / 6;
    var areaEnd = top + height * 5 / 6;
    for (let aniName in scrollAniAreas) {
        let cfg = scrollAniAreas[aniName];
        for (let area of cfg.areas) {
            if (area.in) {
                if (areaEnd < area.top || area.top + area.height < areaStart) {
                    area.in = false;
                    cfg.exit(area.el);
                }
            } else {
                if (areaStart < area.top + area.height && area.top < areaEnd) {
                    area.in = true;
                    cfg.enter(area.el);
                }
            }
        }
    }
}

export {
    emitScrollAniAreas,
    refreshScrollAniAreas,
}